package com.faceCaptor.main;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baidu.speech.restapi.common.DemoException;
import com.baidu.speech.restapi.ttsdemo.AePlayWave;
import com.baidu.speech.restapi.ttsdemo.TtsMain;
import com.faceCaptor.entity.Account;
import com.faceCaptor.entity.User;
import com.faceCaptor.entity.Visit;
import com.faceCaptor.util.*;
import com.ha.facecamera.configserver.DataServer;
import com.ha.facecamera.configserver.*;
import org.apache.log4j.Logger;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.wb.swt.SWTResourceManager;

import java.awt.*;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.stream.Collectors;

public class MainView extends Shell {
    private final static Logger log = Logger.getLogger("logfile");
    private java.util.List<Button> buttonList;
    private java.util.List<Button> folderButtonList;
    private final FormToolkit formToolkit = new FormToolkit(Display.getDefault());
    private final String filePath = "face" + File.separator + DateUtil.getDate();

    private Map<Integer, User> userMap;

    //    private ConfigServer configServer1;
//    private DataServer dataServer1;
//    private ConfigServer configServer2;
//    private DataServer dataServer2;
    private JSONArray devices;
    private byte[] imgData;
    private int[] index = new int[]{0};
    private File[] files;
    static Map<String, Object> cachedmap = new HashMap<String, Object>();
    private int i = 0;
    private Image fImg;
    private JSONObject fjson;
    private String jsonStr = "";
    private LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(3);

    private static Display display;
    private static MainView shell;
    private int folderIndex = 1;

    java.util.List<ConfigServer> configServerList;

    private static boolean tts;

    public MainView(Display display, int style) {

        super(display, style);
//        configServer1 = new ConfigServer();
//        dataServer1 = new DataServer();
//        configServer2 = new ConfigServer();
//        dataServer2 = new DataServer();
        JSONObject config = loadConfig();
        if (config == null) {
            log.error("配置文件出错");
        }
        devices = config.getJSONArray("devices");
        buttonList = new ArrayList<Button>();
        folderButtonList = new ArrayList<Button>();
        userMap = new HashMap<Integer, User>();
        createContents();
//        cachedmap.put("cs", configServer);
        configServerList = new ArrayList<>();
        cachedmap.put("configServerList", configServerList);
    }

    private JSONObject loadConfig() {
        String jarPath = System.getProperty("user.dir");
        String configPath = jarPath + "/config/deviceConfig.json";
        BufferedReader br = null;
        StringBuffer sb = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(configPath), "UTF-8"));
            sb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (sb == null || "".equals(sb.toString())) {
            return null;
        }
        return JSON.parseObject(sb.toString());
    }

    /**
     * Launch the application.
     */

    public static void run(String shopId) {
        display = Display.getDefault();
        cachedmap.put("shopId", shopId);
        Thread th = new Thread(new Runnable() {

            @Override
            public void run() {
                String path = "/face/account/listAll?shopId=" + shopId;
                String jsonStr = HttpUtil.sendGetRequest(HttpUtil.HOST + path);
                JSONArray fjson = JsonUtil.toJsonArray(jsonStr, "data");
                java.util.List<Account> accounts = JSON.parseObject(fjson.toJSONString(), new TypeReference<java.util.List<Account>>() {
                });

                Map<String, String> accountMap = accounts.stream().collect(Collectors.toMap(Account::getRealname, Account::getUsername));
//                System.out.println(accountMap);
                log.info("店员信息：" + accountMap);
                cachedmap.put("employee", accountMap);
            }

        });
        th.start();
        try {
            th.join();
        } catch (InterruptedException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
        shell = new MainView(display, SWT.CLOSE | SWT.MIN);

        shell.open();
        shell.layout();
        shell.addShellListener(new ShellAdapter() {
            public void shellClosed(final ShellEvent e) {
                System.exit(0);
            }
        });

        // });

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }

        display.dispose();

    }

//	public static void main(String[] args) {
//		display = Display.getDefault();
//		cachedmap.put("shopId", "test");
//		shell = new MainView(display, SWT.CLOSE | SWT.MIN);
//
//		shell.open();
//		shell.layout();
//		shell.addShellListener(new ShellAdapter() {
//			public void shellClosed(final ShellEvent e) {
//				System.exit(0);
//			}
//		});
//
//		// });
//
//		while (!shell.isDisposed()) {
//			if (!display.readAndDispatch()) {
//				display.sleep();
//			}
//		}
//
//		display.dispose();
//
//	}

    /**
     * Create contents of the window.
     */
    protected void createContents() {

        Properties properties = new Properties();
        final InputStream resourceAsStream = getClass().getResourceAsStream("/application.properties");
        InputStream in = resourceAsStream;
        try {
            properties.load(in);
            MainView.tts = Boolean.valueOf(properties.getProperty("tts"));
        } catch (IOException e) {
            log.error("加载application.properties失败");
        }
        // this = new this();

        setLocation(new Point(80, 80));
        setMinimumSize(new Point(230, 230));
        setSize(1359, 775);
        setText("人脸捕捉器");
        setLayout(new FormLayout());

        Menu menu = new Menu(this, SWT.BAR);

        setMenuBar(menu);

        MenuItem menuItem = new MenuItem(menu, SWT.NONE);
        menuItem.setText("主页");
        menuItem.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {

                try {
                    Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler http://www.aimendian.cn/");
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });

        MenuItem menuItem_1 = new MenuItem(menu, SWT.RADIO);
        menuItem_1.setText("客户查询");
        menuItem_1.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                try {
                    Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler http://manage.aimendian.cn/face");
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });

        MenuItem menuItem_5 = new MenuItem(menu, SWT.CASCADE);
        menuItem_5.setText("设置");
        Menu menu2 = new Menu(menuItem_5);
        menuItem_5.setMenu(menu2);
        MenuItem menuItem_6 = new MenuItem(menu2, SWT.NONE);
//        System.out.println(tts);
        if (tts) {
            menuItem_6.setText("关闭语音播报");
        } else {
            menuItem_6.setText("打开语音播报");
        }
        menuItem_6.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
            tts = !tts;
            if (tts) {
                menuItem_6.setText("关闭语音播报");
            } else {
                menuItem_6.setText("打开语音播报");
            }
            properties.setProperty("tts", String.valueOf(tts));
                String path = getClass().getResource("/application.properties").getPath();
                FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(path);
                    properties.store(fileOutputStream, "");
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                } catch (IOException e2) {
                    e2.printStackTrace();
                } finally {
                    try {
                        if (null != fileOutputStream){
                            fileOutputStream.close();
                        }
                    } catch (IOException e3) {
                    }
                }
            }
        });

        MenuItem menuItem_2 = new MenuItem(menu, SWT.CASCADE);
        menuItem_2.setText("关于我们");

        Menu menu_1 = new Menu(menuItem_2);
        menuItem_2.setMenu(menu_1);

        MenuItem menuItem_3 = new MenuItem(menu_1, SWT.NONE);
        menuItem_3.setText("联系我们");
        menuItem_3.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {

                ContactDialog contactDialog = new ContactDialog(MainView.this);
                contactDialog.open();

            }
        });

        MenuItem menuItem_4 = new MenuItem(menu_1, SWT.NONE);
        menuItem_4.setText("软件更新");

        menuItem_4.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                UpdateDialog updateDialog = new UpdateDialog(MainView.this);
                updateDialog.open();
            }
        });

        ListViewer listViewer = new ListViewer(this, SWT.BORDER | SWT.H_SCROLL);

        List list = listViewer.getList();
        FormData fd_list = new FormData();
        fd_list.left = new FormAttachment(0, 30);
        fd_list.bottom = new FormAttachment(100, -75);
        list.setLayoutData(fd_list);

        list.select(list.getItemCount() - 1);
        list.showSelection();

        CLabel label = new CLabel(this, SWT.NONE);
        fd_list.top = new FormAttachment(0, 538);
        FormData fd_label = new FormData();
        fd_label.bottom = new FormAttachment(list, -2);
        fd_label.left = new FormAttachment(0, 30);
        label.setLayoutData(fd_label);
        label.setText("最近到访记录");

        CLabel lblNewLabel = new CLabel(this, SWT.NONE);
        lblNewLabel.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 10, SWT.NORMAL));
        FormData fd_lblNewLabel = new FormData();
        fd_lblNewLabel.top = new FormAttachment(0, 20);
        fd_lblNewLabel.left = new FormAttachment(0, 96);
        lblNewLabel.setLayoutData(fd_lblNewLabel);
        lblNewLabel.setAlignment(SWT.CENTER);
        lblNewLabel.setText("客户信息");

        Button btn = new Button(this, SWT.NONE);
        FormData fd = new FormData();
        btn.setLayoutData(fd);
        fd.top = new FormAttachment(0, 20);
        fd.left = new FormAttachment(0, 10);
        formToolkit.adapt(btn, true, true);
        btn.setText("客户查询");
        btn.setVisible(true);

        btn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseUp(MouseEvent e) {
                SearchDialog recordsDialog = new SearchDialog(MainView.this);
                recordsDialog.open();
            }
        });

        Composite composite_img = formToolkit.createComposite(this, SWT.BORDER);
        fd_lblNewLabel.right = new FormAttachment(composite_img, 0, SWT.RIGHT);
        formToolkit.paintBordersFor(composite_img);
        composite_img.setLayout(new FillLayout(SWT.HORIZONTAL));

        FormData fd_lblNewLabel_1 = new FormData(200, 200);
        fd_lblNewLabel_1.left = new FormAttachment(0, 96);
        composite_img.setLayoutData(fd_lblNewLabel_1);

        Composite composite = new Composite(this, SWT.NONE);
        composite.setLayout(new FillLayout());
        // composite.setSize(840,600);

        fd_list.right = new FormAttachment(100, -927);
        fd_label.right = new FormAttachment(100, -1095);
        FormData fd_composite = new FormData();
        fd_composite.bottom = new FormAttachment(list, 0, SWT.BOTTOM);
        fd_composite.top = new FormAttachment(0, 10);
        fd_composite.left = new FormAttachment(list, 24);
        fd_composite.right = new FormAttachment(100, -50);
        composite.setLayoutData(fd_composite);
        formToolkit.paintBordersFor(composite);

        final TabFolder tabFolder = new TabFolder(composite, SWT.BORDER);
        tabFolder.setLayout(new FillLayout());

        TabItem item = new TabItem(tabFolder, SWT.NONE);
        item.setText("实时人脸");

        TabItem item1 = new TabItem(tabFolder, SWT.NONE);
        item1.setText("历史记录");

        TabItem item2 = new TabItem(tabFolder, SWT.NONE);
        item2.setText("查看记录");

        final ScrolledComposite sc1 = new ScrolledComposite(tabFolder, SWT.V_SCROLL | SWT.BORDER);
        sc1.setExpandVertical(true);
        sc1.setExpandHorizontal(true);
        final Composite c1 = new Composite(sc1, SWT.NONE);
        sc1.setContent(c1);

        sc1.setMinSize(840, 1000);
        c1.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
        GridLayout layout = new GridLayout();
        layout.numColumns = 4;
        layout.makeColumnsEqualWidth = true;
        c1.setLayout(layout);

        item.setControl(sc1);


        final ScrolledComposite sc2 = new ScrolledComposite(tabFolder, SWT.V_SCROLL | SWT.BORDER);
        sc2.setExpandVertical(true);
        sc2.setExpandHorizontal(true);
        final Composite c2 = new Composite(sc2, SWT.NONE);
        sc2.setContent(c2);
        // sc2.setMinSize(c2.computeSize(SWT.DEFAULT, SWT.DEFAULT));

        c2.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
        GridLayout layout2 = new GridLayout();
        layout2.numColumns = 4;
        layout2.makeColumnsEqualWidth = true;
        c2.setLayout(layout2);
        sc2.setMinSize(840, 1000);
        c2.layout();
        item1.setControl(sc2);

        final ScrolledComposite sc3 = new ScrolledComposite(tabFolder, SWT.V_SCROLL | SWT.BORDER);
        sc3.setExpandVertical(true);
        sc3.setExpandHorizontal(true);
        final Composite c3 = new Composite(sc3, SWT.NONE);
        sc3.setContent(c3);
        c3.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
        GridLayout layout3 = new GridLayout();
        layout3.numColumns = 4;
        layout3.makeColumnsEqualWidth = true;
        c3.setLayout(layout3);
        sc3.setMinSize(840, 1000);
        c3.layout();
        item2.setControl(sc3);


        tabFolder.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(final SelectionEvent e) {
                if (tabFolder.getSelectionIndex() == 1) {
                    Control[] control = c2.getChildren();
                    for (Control ctl : control) {
                        ctl.dispose();
                    }

                    File filedir = new File(filePath);
                    if (filedir.exists()) {
                        files = filedir.listFiles();

                        int len = files.length;
//                        System.out.println("文件夹中文件的数量:" + len);
                        int group = len / 20;
                        Arrays.sort(files, 0, len, new Comparator<File>() {
                            public int compare(File file, File newFile) {
                                if (file.lastModified() < newFile.lastModified()) {
                                    return 1;
                                } else if (file.lastModified() == newFile.lastModified()) {
                                    return 0;
                                } else {
                                    return -1;
                                }

                            }
                        });
                        if (len % 20 > 0) {
                            group = group + 1;
                        }

                        for (folderIndex = 1; folderIndex <= group; folderIndex++) {
                            Composite folderCom = new Composite(c2, SWT.PUSH);
                            folderCom.setLayoutData(new GridData(192, 192));
                            folderCom.setVisible(true);
                            folderCom.setLayout(new RowLayout(SWT.HORIZONTAL));


                            Button button = new Button(folderCom, SWT.NONE);
                            button.setData(Integer.valueOf(folderIndex));
                            button.setImage(SWTResourceManager.getImage("images/folder.png"));
                            button.setLayoutData(new RowData(190, 150));
                            button.setVisible(true);

                            button.addMouseListener(new MouseAdapter() {
                                @Override
                                public void mouseDoubleClick(MouseEvent e) {

                                    Button source = (Button) e.getSource();
                                    Integer fbListIndex = (Integer) source.getData();
                                    tabFolder.setSelection(item2);
                                    Control[] control = c3.getChildren();
                                    for (Control ctl : control) {
                                        ctl.dispose();
                                    }
                                    int start = 20 * (fbListIndex - 1);
                                    int end = 20 * fbListIndex;
//                                    System.out.println("文件下标" + start + " " + end);
                                    for (int fileIndex = start; fileIndex < end && fileIndex < len; fileIndex++) {
                                        File file = files[fileIndex];
                                        if (file.exists()) {
//                                            System.out.println("文件路径" + file.getAbsolutePath());
                                            Button button = new Button(c3, SWT.PUSH);
                                            button.setData("index", fileIndex);
                                            Image image = SWTResourceManager.getImage(file.getAbsolutePath());
                                            button.setImage(image);
                                            button.setLayoutData(new GridData(192, 192));
                                            button.setVisible(true);
                                            c3.layout();
//                                            System.out.println(file.getName());

                                            String shortName = file.getName().split("\\.")[0];
                                            final String imageName = shortName;
                                            final Image finalImg = image;

                                            button.addMouseListener(new MouseAdapter() {

                                                @Override
                                                public void mouseDoubleClick(MouseEvent e) {
//                                                    System.out.println("文件名" + imageName);
                                                    if (imageName.length() > 19) {
                                                        FormInputDialog inputDialog = new FormInputDialog(MainView.this, finalImg);
                                                        inputDialog.open();
                                                    } else {
                                                        String url = HttpUtil.HOST + HttpUtil.GETUSER + "/" + imageName;
                                                        String jsonStr = HttpUtil.sendGetRequest(url);
                                                        JSONObject fjson = JsonUtil.toJsonObject(jsonStr, "data");
                                                        User user = null;
                                                        if (fjson != null) {
                                                            user = new User();
                                                            user.setId(Integer.valueOf(fjson.getString("id")));
                                                            user.setType(fjson.getString("type"));
                                                            user.setGroup(fjson.getString("group"));
                                                            user.setUserId(fjson.getString("userId"));
                                                            user.setUsername(fjson.getString("username"));
                                                            user.setCreator(fjson.getString("creator"));
                                                        }


                                                        FormInputDialog inputDialog = new FormInputDialog(MainView.this, user, finalImg);
                                                        inputDialog.open();
                                                    }
                                                }
                                            });


                                        }
                                    }

                                }
                            });

                            folderButtonList.add(button);

                            Label folderLabel = new Label(folderCom, SWT.NONE);
                            folderLabel.setLayoutData(new RowData(190, 40));

                            folderLabel.setText(DateUtil.getDate() + " " + folderIndex);
                            folderLabel.setAlignment(SWT.CENTER);

                        }
                        c2.layout();

                    }

                }
            }
        });


        Composite composite_1 = formToolkit.createComposite(this, SWT.BORDER);
        fd_lblNewLabel_1.bottom = new FormAttachment(composite_1, -48);

        Label lblNewLabel_1 = new Label(composite_img, SWT.FILL);
        lblNewLabel_1.setAlignment(SWT.CENTER);

        formToolkit.adapt(lblNewLabel_1, true, true);

        composite_1.setLayout(new GridLayout(2, false));
        FormData fd_composite_1 = new FormData();
        fd_composite_1.left = new FormAttachment(0, 31);
        fd_composite_1.right = new FormAttachment(composite, -24);
        fd_composite_1.bottom = new FormAttachment(label, -6);
        fd_composite_1.top = new FormAttachment(0, 346);
        composite_1.setLayoutData(fd_composite_1);
        formToolkit.paintBordersFor(composite_1);

        CLabel label_2 = new CLabel(composite_1, SWT.NONE);
        formToolkit.adapt(label_2);
        formToolkit.paintBordersFor(label_2);
        label_2.setText("客户姓名");

        CLabel lblNewLabel_2 = new CLabel(composite_1, SWT.NONE);
        GridData gd_lblNewLabel_2 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
        gd_lblNewLabel_2.widthHint = 212;
        lblNewLabel_2.setLayoutData(gd_lblNewLabel_2);
        formToolkit.adapt(lblNewLabel_2);
        formToolkit.paintBordersFor(lblNewLabel_2);

        CLabel label_3 = new CLabel(composite_1, SWT.NONE);
        formToolkit.adapt(label_3);
        formToolkit.paintBordersFor(label_3);
        label_3.setText("客户类型");

        CLabel lblNewLabel_3 = new CLabel(composite_1, SWT.NONE);
        GridData gd_lblNewLabel_3 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
        gd_lblNewLabel_3.widthHint = 212;
        lblNewLabel_3.setLayoutData(gd_lblNewLabel_3);
        formToolkit.adapt(lblNewLabel_3);
        formToolkit.paintBordersFor(lblNewLabel_3);

        CLabel label_4 = new CLabel(composite_1, SWT.NONE);
        formToolkit.adapt(label_4);
        formToolkit.paintBordersFor(label_4);
        label_4.setText("客户群体");

        CLabel lblNewLabel_4 = new CLabel(composite_1, SWT.NONE);
        GridData gd_lblNewLabel_4 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
        gd_lblNewLabel_4.widthHint = 212;
        lblNewLabel_4.setLayoutData(gd_lblNewLabel_4);
        formToolkit.adapt(lblNewLabel_4);
        formToolkit.paintBordersFor(lblNewLabel_4);

        CLabel label_5 = new CLabel(composite_1, SWT.NONE);
        formToolkit.adapt(label_5);
        formToolkit.paintBordersFor(label_5);
        label_5.setText("到访记录");

        CLabel lblNewLabel_5 = new CLabel(composite_1, SWT.NONE);
        formToolkit.adapt(lblNewLabel_5);
        formToolkit.paintBordersFor(lblNewLabel_5);

        Button btnNewButton = new Button(this, SWT.NONE);
        FormData fd_btnNewButton = new FormData();
        fd_btnNewButton.top = new FormAttachment(list, 6);
        fd_btnNewButton.left = new FormAttachment(list, 0, SWT.LEFT);
        btnNewButton.setLayoutData(fd_btnNewButton);
        formToolkit.adapt(btnNewButton, true, true);
        btnNewButton.setText("查看更多到访记录");
        btnNewButton.setVisible(true);

        btnNewButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseUp(MouseEvent e) {
                Button btn = (Button) e.getSource();
                String userId = (String) btn.getData("userId");
                if (userId != null) {
                    RecordsDialog recordsDialog = new RecordsDialog(MainView.this, userId);
                    recordsDialog.open();
                }
            }
        });

        DataServerConfig dsc = new DataServerConfig();
        dsc.connectStateInvokeCondition = ConnectStateInvokeCondition.DeviceNoKnown;
        ConfigServerConfig csc = new ConfigServerConfig();
        csc.noNativeMode = false;
        for (int deviceIndex = 0; deviceIndex < devices.size(); deviceIndex++) {
            JSONObject device = devices.getJSONObject(deviceIndex);
            Integer dataServerPort = device.getInteger("dataServerPort");
            DataServer dataServer = new DataServer();
            boolean ret = dataServer.start(dataServerPort, dsc);
            if (ret) {
//                System.out.println("启动数据服务器成功！\n");
                log.info("启动数据服务器成功");
                dataServer.onCameraConnected((val) -> {
                    try {
                        EventQueue.invokeAndWait(() -> {
                            log.info("设备已连接-数据端口" + val);

                        });
                    } catch (InvocationTargetException e1) {
                        log.error("设备连接出错", e1);
                    } catch (InterruptedException e1) {
                        log.error("设备连接出错", e1);
                    }

                });
                dataServer.onCameraDisconnected((val) -> {

                    try {
                        EventQueue.invokeAndWait(() -> {
                            log.info("设备已断开-数据端口" + val);
                        });
                    } catch (InvocationTargetException e1) {
                        log.error("设备断开出错", e1);
                    } catch (InterruptedException e1) {
                        log.error("设备断开出错", e1);
                    }

                });
                dataServer.onCaptureCompareDataReceived((data) -> {
                    try {
                        EventQueue.invokeAndWait(() -> {

                            if (queue.size() == 0 && data.getPersonRole() != 2) {
                                ArrayList<String> strList = new ArrayList<String>();
                                imgData = data.getFeatureImageData();
                                fjson = null;

                                if (imgData != null) {

                                    ImageData newData = new ImageData(new ByteArrayInputStream(imgData));
                                    ImageData scaleData = ImageUtil.zoomImage(newData, 192, 192);
                                    fImg = new Image(Display.getDefault(), scaleData);
                                    //
                                    // System.out.println("第" + i + "条输出时间(2)：" +
                                    // new Date().getTime());
                                }
                                // 查询会员信息
                                if (data.isPersonMatched()) {

                                    String path = "/face/remark/get/" + data.getPersonID() + "?limit=3";
                                    Thread dataThread = Thread.currentThread();
                                    Thread th1 = new Thread(new Runnable() {

                                        @Override
                                        public void run() {

                                            jsonStr = HttpUtil.sendGetRequest(HttpUtil.HOST + path);
                                            fjson = JsonUtil.toJsonObject(jsonStr, "data");

                                        }

                                    });
                                    th1.start();
                                    try {
                                        th1.join();
                                    } catch (InterruptedException e2) {
                                        // TODO Auto-generated catch block
                                        e2.printStackTrace();
                                    }
                                }

                                display.asyncExec(new Runnable() {
                                    @Override
                                    public void run() {
                                        Visit visit = new Visit();
                                        String filename = "";

                                        if (fjson != null) {
                                            User user = new User();

                                            if (fjson.containsKey("username")) {
                                                lblNewLabel_2.setText(fjson.getString("username"));
                                                user.setUsername(fjson.getString("username"));
                                            }
                                            if (fjson.containsKey("type")) {
                                                lblNewLabel_3.setText(fjson.getString("type"));
                                                user.setType(fjson.getString("type"));
                                            }
                                            if (fjson.containsKey("group")) {
                                                lblNewLabel_4.setText(fjson.getString("group"));
                                                user.setGroup(fjson.getString("group"));
                                            }
                                            if (fjson.containsKey("mobilephone")) {
                                                user.setMobilephone(fjson.getString("mobilephone"));
                                            }

                                            if (fjson.containsKey("id")) {
                                                user.setId(Integer.valueOf(fjson.getString("id")));

                                            }
                                            if (fjson.containsKey("creator")) {
                                                user.setCreator(fjson.getString("creator"));
                                            }
                                            if (fjson.containsKey("userId")) {
                                                user.setUserId(fjson.getString("userId"));
                                                userMap.put(index[0], user);
                                                btnNewButton.setData("userId", fjson.getString("userId"));
                                                Thread wxPushThread = new Thread(() -> {
                                                    String path = "/face/push?userId=" + fjson.getString("userId");
                                                    HttpUtil.sendGetRequest(HttpUtil.HOST + path);
                                                });
                                                wxPushThread.start();
                                                try {
                                                    wxPushThread.join();
                                                } catch (InterruptedException e2) {
                                                    e2.printStackTrace();
                                                }
                                            }

                                            visit.setShopId(fjson.getString("shopId"));
                                            visit.setUserId(fjson.getString("userId"));
                                            visit.setUsername(fjson.getString("username"));
                                            filename = fjson.getString("userId") + ".png";
                                        } else {
                                            visit.setShopId((String) cachedmap.get("shopId"));
                                            String uuid = UUID.randomUUID().toString();
                                            uuid = uuid.replace("-", "");
                                            visit.setUserId(uuid);
                                            visit.setUsername("非会员");
                                            lblNewLabel_2.setText("");
                                            lblNewLabel_3.setText("");
                                            lblNewLabel_4.setText("");
                                            filename = uuid + ".png";
                                        }

                                        Thread th2 = new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                HttpUtil.postSwtForm(HttpUtil.HOST + HttpUtil.SAVEVISIT, visit);
                                            }
                                        });
                                        th2.start();

                                        if (fImg != null) {
                                            if (index[0] >= 20) {
                                                Control[] control = c1.getChildren();
                                                for (Control ctl : control) {
                                                    ctl.dispose();
                                                }

                                                User user = userMap.get(index[0]);
                                                index[0] = index[0] % 20;

                                                userMap.clear();
                                                if (user != null) {
                                                    userMap.put(index[0], user);
                                                }
                                            }
//										Button btn = buttonList.get(index[0]);

                                            Button btn = new Button(c1, SWT.PUSH);
                                            btn.setLayoutData(new GridData(192, 192));
                                            btn.setData("index", index[0]);
//										btn.setVisible(true);


                                            btn.addMouseListener(new MouseAdapter() {

                                                @Override
                                                public void mouseDoubleClick(MouseEvent e) {
                                                    Button button = (Button) e.getSource();
                                                    int btnIndex = (int) btn.getData("index");
                                                    if (userMap.containsKey(btnIndex) && userMap.get(btnIndex) != null) {

                                                        FormInputDialog fid = new FormInputDialog(MainView.this, userMap.get(btnIndex), button.getImage());
                                                        fid.open();

                                                    } else {
                                                        FormInputDialog fid = new FormInputDialog(MainView.this, button.getImage(), imgData);
                                                        fid.open();
                                                    }

                                                }

                                            });
                                            log.info("第" + i + "条输出时间(3)：" + new Date());
                                            btn.setImage(fImg);
                                            btn.setVisible(true);
                                            c1.layout();
                                            lblNewLabel_1.setImage(fImg);
                                            // 把图片写到本地缓存
                                            File filedir = new File(filePath);
                                            if (!filedir.exists()) {
                                                filedir.mkdirs();
                                            }
                                            FileUtil.save(filePath, filename, ImageUtil.imageToByte(fImg));
                                            index[0]++;


                                            i++;
                                        }

                                    }

                                });

                                if (data.isPersonMatched()) {
                                    if (fjson != null) {

                                        JSONArray array = fjson.getJSONArray("remarkList");

                                        String username = fjson.getString("username");
                                        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
                                        if (tts) {
                                            TtsMain ttsmain = new TtsMain();

                                            AePlayWave apw = new AePlayWave(queue);
                                            String resultWav = "result";
                                            try {
                                                ttsmain.run("您好，" + username, resultWav);
                                            } catch (IOException e1) {
                                                log.error(e1);
                                            } catch (DemoException e1) {
                                                log.error(e1);
                                            }

                                            String wavfile = resultWav + ".wav";
                                            if (new File(wavfile).exists()) {

                                                try {
                                                    queue.put(wavfile);
                                                } catch (InterruptedException e1) {
                                                    log.error(e1);
                                                }
                                                new Thread(apw).start();

                                            }
                                        }


                                        for (int i = 0; i < array.size(); i++) {
                                            JSONObject remarkObj = array.getJSONObject(i);
                                            String detail = remarkObj.getString("detail");

                                            Date time = new Date(remarkObj.getLong("updateTime"));
                                            if (detail != null && !detail.equals("")) {
                                                strList.add(username + "," + format.format(time) + "," + detail);
                                                try {
                                                    Thread.sleep(100);
                                                } catch (InterruptedException e) {
                                                    log.error(e);
                                                }
                                            }

                                        }
                                    }

                                }
                                display.asyncExec(new Runnable() {

                                    @Override
                                    public void run() {
                                        // TODO Auto-generated method stub
                                        list.removeAll();
                                        for (int j = 0; j < strList.size(); j++) {
                                            list.add(strList.get(j));
                                        }
                                    }
                                });

                            }
                        });

                    } catch (InvocationTargetException e3) {
                        log.error("接收数据出错", e3);
                    } catch (InterruptedException e3) {
                        log.error("接收数据出错", e3);
                    }

                });

                dataServer.onAuthing((time, username, password) -> {
                    // XXX 如果要校验用户名密码，请使用如下代码
                    // return username.equals("xiaohe") &&
                    // Util.judgeRegPassword(time, "123456", password);
                    System.out.println(
                            String.format("dataServer 收到鉴权消息username=>%s password=>%s", username, new String(password)));
                    return true;
                });
            }
            ConfigServer configServer = new ConfigServer();
            Integer configServerPort = device.getInteger("configServerPort");
            boolean cret = configServer.start(configServerPort, csc);
            if (cret) {
                log.info("启动配置服务器成功!");
                configServer.onCameraConnected((val) -> {

                    try {
                        EventQueue.invokeAndWait(() -> {
                            log.info("设备已连接-配置端口" + val);
//                            System.out.println("设备已连接-配置端口 ");
//                            System.out.println(val);
//                            System.out.println("\n\tAppConfig:\n\t\t");
//                            System.out.println(configServer.getAppConfig(val).toJson());
//                            System.out.println("\n\tVersion:\n\t\t");
//                            System.out.println(configServer.getVersion(val).toJson());
//                            System.out.println("\n");
                            configServerList.add(configServer);
                        });
                    } catch (InvocationTargetException e1) {
                        log.error("设备连接失败", e1);
                    } catch (InterruptedException e1) {
                        log.error("设备连接失败", e1);
                    }

                });

                configServer.onCameraDisconnected((val) -> {

                    try {
                        EventQueue.invokeAndWait(() -> {
                            log.info("设备已断开-配置端口 " + val);
//                            System.out.println("设备已断开-配置端口 ");
//                            System.out.println(val);
//                            System.out.println("\n\tAppConfig:\n\t\t");
//                            System.out.println(configServer.getAppConfig(val).toJson());
//                            System.out.println("\n\tVersion:\n\t\t");
//                            System.out.println(configServer.getVersion(val).toJson());
//                            System.out.println("\n");
                            configServerList.remove(configServer);
                        });
                    } catch (InvocationTargetException e1) {
                        log.error("设备端口出错", e1);
                    } catch (InterruptedException e1) {
                        log.error("设备端口出错", e1);
                    }

                });
                configServer.onAuthing((time, username, password) -> {
                    // XXX 如果要校验用户名密码，请使用如下代码
                    // return username.equals("xiaohe") &&
                    // Util.judgeRegPassword(time, "123456", password);
                    System.out.println(
                            String.format("configServer 收到鉴权消息username=>%s password=>%s", username, new String(password)));
                    return true;
                });
            }
        }
    }

    @Override
    protected void checkSubclass() {
        // Disable the check that prevents subclassing of SWT components
    }

    public Point getDtLocation(int x, int y) {
        return new Point(this.getLocation().x + x, this.getLocation().y + y);
    }

    public Image scaleImage(Image img) {
        Image scaled = new Image(Display.getDefault(), 200, 200);

        GC gc = new GC(scaled);
        try {
            gc.setAdvanced(true); // 打开高级绘图模式
            gc.setAntialias(SWT.ON);// 设置消除锯齿
            gc.setInterpolation(SWT.HIGH); // 设置插值
            gc.drawImage(img, 0, 0, img.getBounds().width, img.getBounds().height, 0, 0, 200, 200);
        } finally {
            gc.dispose();
        }
        return scaled;
    }

    public void getThreads() {
        ThreadGroup group = Thread.currentThread().getThreadGroup();
        ThreadGroup topGroup = group;
        // 遍历线程组树，获取根线程组
        while (group != null) {
            topGroup = group;
            group = group.getParent();
        }
        // 激活的线程数加倍
        int estimatedSize = topGroup.activeCount() * 2;
        Thread[] slackList = new Thread[estimatedSize];
        // 获取根线程组的所有线程
        int actualSize = topGroup.enumerate(slackList);
        // copy into a list that is the exact size
        Thread[] list = new Thread[actualSize];
        System.arraycopy(slackList, 0, list, 0, actualSize);
        System.out.println("Thread list size == " + list.length);
        for (Thread thread : list) {
            System.out.println(thread.getName());
        }
    }

}
